<template>
	<view class="page-content">
		<u-cell-group>
			<u-cell-item :value="getGoodsText" @click="changeGetGoods">
				<view class="custom-cell-label required" slot="title">是否收到商品</view>
			</u-cell-item>
		</u-cell-group>
		<view>
			<u-cell-group>
				<u-cell-item :value="goodsNumVal" @click="goodsNumHandle">
					<view class="custom-cell-label required" slot="title">退货数量</view>
				</u-cell-item>
				<u-cell-item :arrow="false">
					<view class="custom-cell-label required" slot="title">退款金额</view>
					<view class="custom-cell-val" slot="right-icon">
						<u-input v-model="amount" input-align="right" :placeholder="amountPlaceholder" :maxlength="12"
							type="digit" @input="amountInputHandle"></u-input>
					</view>
				</u-cell-item>
				<view class="full-cell-item">
					<view class="full-cell-title required">退款说明</view>
					<view class="full-cell-content"><u-input v-model="refundNote" type="textarea" placeholder="请输入退款说明"
							:maxlength="300"></u-input></view>
				</view>
				<view class="full-cell-item">
					<view class="full-cell-title required">上传图片</view>
					<view class="full-cell-content"><u-upload :action="uploadUrl" :header="requestStaticHeader"
							:max-count="5" ref="imgUpload"></u-upload></view>
				</view>
			</u-cell-group>
		</view>
		<!-- 选择商品数量 -->

		<u-popup v-model="goodsNumVisible" mode="bottom" safe-area-inset-bottom :mask-close-able="false">
			<view class="get-goods-content">
				<view class="get-goods-header am-flex-rc-between">
					<view class="hd-btn" @click="goodsNumVisible = false">取消</view>
					<view class="hd-title">请选择退款数量</view>
					<view class="hd-btn confirm-btn" @click="goodsNumVisible = false">确定</view>
				</view>
				<scroll-view scroll-y="true" class="get-goods-scroll">
					<view class="order-goods-wrap">
						<view class="order-goods-box" v-for="list in orderSelectGoods" :key="list.productVO.pid">
							<view class="product-goods">
								<view class="product-goods-cover">
									<image :src="list.my_self_cover" mode="aspectFill"
										class="order-card__goods-img am-block am-wh-100"></image>
								</view>
								<view class="product-goods-con">
									<view class="product-goods-main">
										<view class="product-goods-title">
											<text class="am-text-break am-line-clamp-two">{{ list.productVO.name
												}}</text>
											<text class="specStyle">{{ list.productVO.spec }}</text>
										</view>
										<view class="product-goods-price original-price">原价: {{ orderDetails.originalPrice
											}}</view>
										<view class="product-goods-price">{{ list.orderPrice }}元x{{ list.num }}</view>
									</view>
									<view class="product-goods-total am-text-eill">￥{{ list.my_self_total }}</view>
								</view>
							</view>
							<view class="refund-goods-ft am-flex-rc-between">
								<view class="refund-goods-num-max">可退数量：{{ list.num }}</view>
								<view class="pedometer-wrap">
									<u-number-box v-model="list.my_self_refund_num" :long-press="false"
										@change="goodsNumChange" :min="1" :max="list.num" :input-height="54"
										:input-width="86"></u-number-box>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		<!-- 选择商品数量 end-->
		<view class="submit-wrap am-flex-rc-between"><button class="u-reset-button co-primary-button submit-btn"
				@click="submit">提交申请</button></view>
		<view class="submit-wrap-place"></view>
	</view>
</template>

<script>
import { apiOrderDetails, apiOrderAfter } from '@/api/order.js';
import { UPDATE_ORDER_LIST, UPDATE_ORDER_DETAILS } from '@/types/globalEventName';
import { UPLOAD_URL } from '@/api/common';
import { requestStaticHeader } from '@/request/config.js';
import Big from 'big.js';
const getGoodsType = [{ key: 'has', label: '已收到全部（或部分）商品', value: '1' }, { key: 'no', label: '未收到商品（包含未签收）', value: '0' }];
export default {
	data() {
		return {
			submitLoading: false,
			amount: '', // 退款金额
			refundNote: '', // 退款说明
			amountPlaceholder: '请输入',
			orderSelectGoods: [],
			goodsNumVal: '共计0件',
			uploadUrl: UPLOAD_URL,
			requestStaticHeader: {},
			getGoodsText: '请选择',
			getGoodsSelVal: '', // 是否收到商品
			orderDetails: {},
			goodsNumVisible: false,
			refunAmount: 0
		};
	},
	/**
	 * @param {Object} options - 页面参数
	 * @param {String} options.orderId - 订单id
	 * @param {String} options.goodsPids - 选中的商品pid 集合
	 * */
	onLoad(options) {
		this.pageQuery = options;
		if (options.orderId) {
			this.getDetails();
		}
		this.requestStaticHeader = {
			...requestStaticHeader,
			Authorization: this.$store.getters.isLogin ? `Bearer ${this.$store.state.token}` : ''
		};
	},
	methods: {
		getDetails() {
			uni.showLoading({
				mask: true
			});
			apiOrderDetails({ id: this.pageQuery.orderId })
				.then(res => {
					let { state, data, msg } = res.data;
					if (state === 'OK') {
						let imageCutting = this.$imageCutting;
						let orderSelectGoods = [];
						let pidsStr = decodeURIComponent(this.pageQuery.goodsPids || '');
						let selectPids = pidsStr.split(',');
						console.log(selectPids);
						data.orderDetailVOList.forEach(p1 => {
							if (selectPids.includes(p1.productVO.pid)) {
								p1.my_self_total = Number(new Big(p1.orderPrice).times(p1.num));
								p1.my_self_cover = imageCutting(p1.productVO.banner.split(',')[0], 120, 120);
								p1.my_self_refund_num = p1.num;
								orderSelectGoods.push(p1);
							}
						});
						this.refunAmount = data.price;
						this.orderSelectGoods = orderSelectGoods;
						this.goodsNumVal = `共计${orderSelectGoods.length}件`;
						this.amountPlaceholder = `请输入，不超过￥${data.price}`;
						this.orderDetails = data;
						uni.hideLoading();
					} else {
						uni.hideLoading();
						this.$am_toast.warning(msg);
					}
				})
				.catch(err => {
					console.log(err);
					uni.hideLoading();
					this.$am_toast.error('查询失败，请重新尝试！');
				});
		},
		submit() {
			console.log(this.amount);
			if (this.submitLoading) return;
			let imgList = [];
			this.$refs.imgUpload.lists.forEach(p1 => {
				console.log(p1.response);
				if (p1.progress === 100 && p1.response && p1.response.state === 'OK') {
					imgList.push(p1.response.data.url);
				}
			});
			if (this.getGoodsSelVal === '') {
				this.$am_toast('请选择是否收到商品');
				return;
			} else if (this.amount === 0 || this.amount > this.refunAmount) {
				this.$am_toast('退款金额不正确');
				return;
			} else if (!this.refundNote) {
				this.$am_toast('请输入退款说明');
				return;
			} else if (imgList.length === 0) {
				this.$am_toast('请上传图片');
				return;
			}
			this.submitLoading = true;
			let afterSalesOrdersDetailDTOList = this.orderSelectGoods.map(p1 => {
				return {
					num: p1.my_self_refund_num,
					pid: p1.productVO.pid,
					sku: p1.productVO.sku
				};
			});
			let p_data = {
				afterSalesOrdersDetailDTOList: afterSalesOrdersDetailDTOList,
				applyRemark: this.refundNote,
				isGetProduct: this.getGoodsSelVal,
				oid: this.orderDetails.oid,
				photo: imgList.toString(),
				prices: this.amount,
				num: this.orderSelectGoods.length
			};

			apiOrderAfter(p_data)
				.then(res => {
					uni.hideLoading();
					let { state, msg } = res.data;
					if (state === 'OK') {
						uni.$emit(UPDATE_ORDER_LIST);
						uni.$emit(UPDATE_ORDER_DETAILS, { id: this.pageQuery.orderId });
						uni.navigateBack({
							delta: 2
						});
						this.$am_toast.success('提交成功');
					} else {
						this.$am_toast.warning(msg);
					}
					this.submitLoading = false;
				})
				.catch(() => {
					this.submitLoading = false;
					uni.hideLoading();
					this.$am_toast.error('操作失败，请重新尝试！');
				});
		},
		// 是否收到商品
		changeGetGoods() {
			uni.showActionSheet({
				itemList: getGoodsType.map(p1 => p1.label),
				itemColor: '#333',
				success: goodsRes => {
					console.log(goodsRes);
					this.getGoodsText = getGoodsType[goodsRes.tapIndex].label;
					this.getGoodsSelVal = getGoodsType[goodsRes.tapIndex].value;
				}
			});
		},
		amountInputHandle(e) {
			console.log(e);
			let val = e;
			if (e) {
				let strVal = e.toString();
				let zeIndex = strVal.indexOf('.');
				if (zeIndex > -1 && strVal.length - zeIndex > 3) {
					strVal = strVal.slice(0, zeIndex + 3);
					val = Number(strVal);
					console.log('val-2', val);
				}
				if (e > this.refunAmount) {
					val = this.refunAmount;
					console.log('val-3', val);
				}
				setTimeout(() => {
					this.amount = val;
				}, 0);
			}
		},
		//
		goodsNumHandle() {
			this.goodsNumVisible = true;
		},
		goodsNumChange() {
			console.log(22222222);
			let total = new Big(0);
			this.orderSelectGoods.forEach(p1 => {
				total = total.plus(new Big(p1.my_self_refund_num).times(p1.orderPrice));
			});
			this.amount = Number(total);
			this.refunAmount = Number(total);
			this.amountPlaceholder = `请输入，不超过￥${Number(total)}`;
		}
	}
};
</script>

<style lang="scss" scoped>
.custom-cell-label {
	font-size: 30rpx;
	color: #666;

	&.required {
		&::after {
			content: '*';
			color: red;
		}
	}
}

.custom-cell-val {
	width: 450rpx;
	font-size: 30rpx;
	color: #333;
}

.page-content {
	padding-top: 16rpx;
}

.submit-wrap-place {
	height: 100rpx;
}

.submit-wrap {
	position: fixed;
	left: 0;
	height: 100rpx;
	width: 750rpx;
	bottom: 0;
	z-index: 2000;
	background-color: #fff;
}

.submit-btn {
	width: 690rpx;
}

.full-cell-item {
	padding: 30rpx 30rpx;
}

.full-cell-title {
	font-size: 30rpx;
	color: #666;

	&.required {
		&::after {
			content: '*';
			color: red;
		}
	}
}

.full-cell-content {
	margin-top: 30rpx;
}

.get-goods-content {
	// width: 750rpx;
}

.get-goods-header {
	border-bottom: 1px solid #dddddd;

	.hd-btn {
		height: 84rpx;
		line-height: 84rpx;
		padding: 0 30rpx;
		font-size: 34rpx;
		color: #333333;
	}

	.hd-title {
		font-size: 34rpx;
		color: #000000;
	}

	.confirm-btn {
		color: #108ee9;
	}
}

.get-goods-scroll {
	height: 600rpx;
}

.order-goods-wrap {
	padding: 0 30rpx;
}

.order-goods-box {
	padding: 28rpx 0;

	&+.order-goods-box {
		border-top: 1px dashed #e8e8e8;
	}
}

.product-goods {
	display: flex;
}

.product-goods-cover {
	overflow: hidden;
	flex-shrink: 0;
	width: 120rpx;
	height: 120rpx;
	border-radius: 8rpx;
}

.order-card__goods-img {}

.product-goods-con {
	display: flex;
	flex: 1;
	width: 0;
	margin-left: 10rpx;
	align-items: center;
}

.product-goods-main {
	flex: 1;
	width: 0;
}

.product-goods-title {
	height: 80rpx;
	font-size: 30rpx;
	color: #333333;
	line-height: 42rpx;
}

.product-goods-price {
	font-size: 24rpx;
	color: #999999;
}

.product-goods-total {
	width: 140rpx;
	padding-left: 15rpx;
	flex-shrink: 0;
	text-align: right;
	font-size: 30rpx;
	color: #333333;
}

.refund-goods-ft {
	margin-top: 22rpx;
}

.refund-goods-num-max {
	font-size: 26rpx;
	color: #666666;
}

.pedometer-wrap {
	/deep/ .u-icon-disabled {
		color: #ccc;
	}

	/deep/ .u-icon-minus {
		background: transparent !important;
	}

	/deep/ .u-icon-plus {
		background: transparent !important;
	}
}

.specStyle {
	margin-top: 10rpx;
	padding: 5rpx 10rpx;
	background: rgba(239, 239, 244, 0.5);
	color: #999999;
	border-radius: 4rpx;
	font-size: 22rpx;
}
</style>
